#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "memoryitemmodel.h"
#include "memory.h"
#include "machine.h"
#include "cpu.h"

#include <QFileDialog>

#include <iostream>

using namespace std;

const quint32 MainWindow::BEGIN_ADDRESS = 4096;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow), machine(Machine::getInstance(this))
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::on_actionLoad_Program_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"./",tr("Obj (*.obj)"));
    if(!fileName.isEmpty())
    {
        quint32 pc = Machine::getInstance()->loadProgram(fileName);
        machine->getCPU()->setPC(pc);
        ui->memoryWidget->goToAddress(pc);
    }
}

void MainWindow::on_actionRun_triggered()
{
    ui->actionStop->setEnabled(true);
    ui->actionRun->setEnabled(false);
    machine->run();
}

void MainWindow::on_actionStop_triggered()
{
    ui->actionRun->setEnabled(true);
    ui->actionStop->setEnabled(false);
    machine->stop();
}

void MainWindow::on_actionStep_Over_triggered()
{
    machine->step_over();
    ui->actionRun->setEnabled(true);
    ui->actionStop->setEnabled(false);
}

void MainWindow::on_actionStep_Into_triggered()
{
    machine->step_into();
    ui->actionRun->setEnabled(true);
    ui->actionStop->setEnabled(false);
}

void MainWindow::on_actionStep_Out_triggered()
{
    machine->step_out();
    ui->actionRun->setEnabled(true);
    ui->actionStop->setEnabled(false);
}

void MainWindow::on_actionSet_PC_triggered()
{
    quint32 address = ui->memoryWidget->selectedPC();
    machine->getCPU()->setPC(address);
}
